package com.example.yinhangmiaosha.interceptor;

import com.example.yinhangmiaosha.domain.User;
import com.example.yinhangmiaosha.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LimitInterceptor implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(LimitInterceptor.class);

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("LimitInterceptor拦截");
        if (handler instanceof HandlerMethod) {
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            try {
                boolean isBanned = userService.getUserIsBanned(user.getId());
                if (isBanned) {
                    LOGGER.error("[{}]：访问系统超过频率限制！", user.getUserName());
                    response.sendRedirect("/nopermission");
                    return false;
                }
                int count = userService.addUserCount(user.getId());
                LOGGER.info("[{}]：截至该次的访问次数为: [{}]", user.getUserName(), count);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
